package com.zhengshang.api.task.payorder;

import com.zhengshang.api.domain.AppPayRecord;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

public class PayOrderCollection {
    /**
     * 支付订单管理集合
     */
    private static DelayQueue<AppPayRecord> payOrderList = new DelayQueue<AppPayRecord>();
    private PayOrderCollection() {
    }
    /**
     * 获取支付订单集合
     * @author HY
     * @return
     */
    public static DelayQueue getOrderCollection() {
        return payOrderList;
    }
    /**
     * 向集合中添加支付订单
     *
     * @author HY
     * @param appPayRecord
     * @return
     */
    public static boolean add(AppPayRecord appPayRecord) {
        boolean flag = false;
        if (appPayRecord != null && StringUtils.isNotBlank(appPayRecord.getOrderNum())) {
            flag = payOrderList.offer(appPayRecord);
        }
        return flag;
    }
    /**
     * 从集合中删除支付订单
     *
     * @author HY
     * @param ordernum
     * @return
     */
    public static boolean remove(String ordernum) {
        boolean flag = false;
        AppPayRecord thisOrder = null;
        if (StringUtils.isNotBlank(ordernum)) {
            ordernum = ordernum.trim();
            for (AppPayRecord appPayRecord : payOrderList) {
                String orderNum = appPayRecord.getOrderNum();
                if (orderNum.equals(ordernum)) {
                    thisOrder = appPayRecord;
                }
            }
            if (thisOrder != null) {
                flag = payOrderList.remove(thisOrder);
            }
        }
        return flag;
    }
    /**
     * 获取支付订单的过期剩余时间
     *
     * @author HY
     * @param ordernum
     * @return -1 已经过期
     */
    public static long getDelay(String ordernum) {
        long time = -1;
        if (StringUtils.isNotBlank(ordernum)) {
            ordernum = ordernum.trim();
            for (AppPayRecord appPayRecord : payOrderList) {
                String orderNum = appPayRecord.getOrderNum();
                if (orderNum.equals(ordernum)) {
                    time = appPayRecord.getDelay(TimeUnit.MILLISECONDS);
                    if(time < 5000) {
                        time = -1;
                    }
                }
            }
        }
        return time;
    }
}
